package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.Analysis;
import com.tanhua.model.domain.Log;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.DateVo;
import com.tanhua.model.vo.UsersStatisticsVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AnalysisService {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private AnalysisMapper analysisMapper;
    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 定时统计tb_log表中的数据，保存或者更新tb_analysis表
     *  1、查询tb_log表（注册用户数，登录用户数，活跃用户数，次日留存）
     *  2、构造Analysis对象
     *  3、保存或者更新
     */
    public void analysis() throws ParseException {
        //1、定义查询的日期
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesdayStr = DateUtil.yesterday().toString("yyyy-MM-dd");
        //2、统计数据-注册数量
        Integer regCount = logMapper.queryByTypeAndLogTime("0102", todayStr);
        //3、统计数据-登录数量
        Integer loginCount = logMapper.queryByTypeAndLogTime("0101", todayStr);
        //4、统计数据-活跃数量
        Integer activeCount = logMapper.queryByLogTime(todayStr);
        //5、统计数据-次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(todayStr, yesdayStr);
        //6、构造Analysis对象
        //7、根据日期查询数据
        QueryWrapper<Analysis> qw = new QueryWrapper<Analysis>();
        qw.eq("record_date",new SimpleDateFormat("yyyy-MM-dd").parse(todayStr));
        Analysis analysis = analysisMapper.selectOne(qw);
        //8、如果存在，更新，如果不存在保存
        if(analysis != null) {
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        }else {
            analysis = new Analysis();
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(todayStr));
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        }
    }

    //累计用户数
    public Integer queryCumulativeUsers() {
        return analysisMapper.queryCumulativeUsers();
    }

    //根据当前时间查询AnalysisByDay  今日统计信息数据
    public Analysis querySummary(Date now) {
        //构建条件查询
        LambdaQueryWrapper<Analysis>qw= Wrappers.<Analysis>lambdaQuery();
        qw.eq(Analysis::getRecordDate,DateUtil.format(now,"yyyy-MM-dd"));   //hutool工具包  计算日期的工具类
        //调用方法查询
        return analysisMapper.selectOne(qw);
    }
    //查询过去30天活跃用户数
    public Integer getNumActivePassMonth() {
        return analysisMapper.getNumActivePassMonth();
    }
    //查询过去7天活跃用户数
    public Integer getNumActivePassWeek() {
        return analysisMapper.getNumActivePassWeek();
    }

    //次日留存统计
    public UsersStatisticsVo getUsers(Long sd, Long ed, Long type) {
        //sd 起始时间    ed结束时间  type 101新增 102活跃 103次日留存
        UsersStatisticsVo analysisUsersVo = new UsersStatisticsVo();
        List<DateVo> thisYear = new ArrayList<>();
        List<DateVo> lastYear = new ArrayList<>();
        //类型 101 新增
        if (type==101){
            //设置起始时间
            Calendar sdate = Calendar.getInstance(); //设置起始时间
            sdate.setTime(new Date(sd));
            sdate.add(Calendar.YEAR, -1);
            Date sdTime = sdate.getTime();
            Calendar edate = Calendar.getInstance();//设置结束时间
            edate.setTime(new Date(ed));
            edate.add(Calendar.YEAR, -1);
            Date edTime = edate.getTime();
            //定义一个集合用来存储查询到符合时间区间的数据的月份
            List<Integer> months = new ArrayList<>();
            List<UserInfo> thislogs = userInfoApi.findAlls();
            //将符合条件的数据存储到新的集合中
            List<UserInfo> newThisLogs = new ArrayList<>();
            for (UserInfo thislog : thislogs) {
                long time = thislog.getCreated().getTime();//获取该用户的创建时间
                if (time >= sd && time <= ed) {
                    //时间符合的存入 新的集合中
                    newThisLogs.add(thislog);
                }
            }
            //将新的集合中的月份取出来存入到集合中
            for (UserInfo log : newThisLogs) {
                Date date = log.getCreated();
                int month = date.getMonth();
                months.add(month);

            }
            //一年12个月
            int s = 0;
            for (int i = 1; i <= 12; i++) {
                DateVo dateVo = new DateVo();
                //设置日期(即便利月份 一年12个月)
                dateVo.setTitle(String.valueOf((i)));
                //取得每个月的数据数量
                for (Integer month : months) {
                    if ((month + 1) == i) {
                        s++;
                    }
                }
                dateVo.setAmount((long) s);
                thisYear.add(dateVo);
                //将s重置为0以用来取下个月份的数据数量
                s = 0;
            }
            List<Integer> monthe = new ArrayList<>();
            List<UserInfo> lastlogs = userInfoApi.findAlls();
            List<UserInfo> newLastLogs = new ArrayList<>();
            for (UserInfo lastlog : lastlogs) {
                long time = lastlog.getCreated().getTime();
                if (time >= sdTime.getTime() && time <= edTime.getTime()) {
                    newLastLogs.add(lastlog);
                }
            }
            for (UserInfo log : newLastLogs) {
                Date date = log.getCreated();
                int month = date.getMonth();
                monthe.add(month);
            }
            int e = 0;
            for (int i = 1; i <= 12; i++) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(String.valueOf((i)));
                for (Integer month : monthe) {
                    if ((month + 1) == i) {
                        e++;
                    }
                }
                dateVo.setAmount((long) e);
                lastYear.add(dateVo);
                e = 0;
            }
        }
        //活跃用户
        if (type == 102) {
            QueryWrapper<Log> thisqueryWrapper = new QueryWrapper<>();
            Calendar sdate = Calendar.getInstance();
            sdate.setTime(new Date(sd));
            sdate.add(Calendar.YEAR, -1);
            Date sdTime = sdate.getTime();
            Calendar edate = Calendar.getInstance();
            edate.setTime(new Date(ed));
            edate.add(Calendar.YEAR, -1);
            Date edTime = edate.getTime();
            thisqueryWrapper.between("log_time", sd, ed);
            List<Integer> months = new ArrayList<>();
            List<Log> thislogs = this.logMapper.selectList(thisqueryWrapper);
            for (Log log : thislogs) {
                Date date = new Date(log.getLogTime());
                int month = date.getMonth();
                months.add(month);

            }
            int s = 0;
            for (int i = 1; i <= 12; i++) {
                DateVo dateVo = new DateVo();

                dateVo.setTitle(String.valueOf((i)));
                for (Integer month : months) {
                    if ((month + 1) == i) {
                        s++;
                    }
                }
                dateVo.setAmount((long) s);
                thisYear.add(dateVo);
                s = 0;
            }
            QueryWrapper<Log> lastqueryWrapper = new QueryWrapper<>();
            lastqueryWrapper.between("log_time", sdTime.getTime(), edTime.getTime());
            List<Integer> monthe = new ArrayList<>();
            List<Log> lastlogs = this.logMapper.selectList(lastqueryWrapper);
            for (Log log : lastlogs) {
                Date date = new Date(log.getLogTime());
                int month = date.getMonth();
                monthe.add(month);
            }
            int e = 0;
            for (int i = 1; i <= 12; i++) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(String.valueOf((i)));
                for (Integer month : monthe) {
                    if ((month + 1) == i) {
                        e++;
                    }
                }
                dateVo.setAmount((long) e);
                lastYear.add(dateVo);
                e = 0;
            }

        }
        //次日留存统计
        if (type == 103) {

        }
        analysisUsersVo.setThisYear(thisYear);
        analysisUsersVo.setLastYear(lastYear);
        return analysisUsersVo;
    }
}
